﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web.Script.Serialization;
using OnePiece.Core.Extension.Paging;


namespace OnePiece.Ui.Controls
{
    public class GridPageHelper : PageExtensionHelper
    {
        private readonly string _jsonFilterString;
        public GridPageHelper(NameValueCollection httpContext)
        {
            PageIndex = (httpContext["page"] == null) ? DefaultPageIndex : Int32.Parse(httpContext["page"]);
            PageSize = (httpContext["rows"] == null) ? DefaultPageSize : Int32.Parse(httpContext["rows"]);
            _jsonFilterString = httpContext["filters"] ?? string.Empty;
            var sortName = httpContext["sidx"] ?? string.Empty;
            var sortOrder = httpContext["sord"] ?? string.Empty;

            //build the sortString            
            SortString = string.IsNullOrEmpty(sortName) ? "" : sortName + " " + sortOrder;

        }

        private PageExtensionHelperFilter _filter;
        public override PageExtensionHelperFilter Filter
        {
            get
            {
                if (_filter == null)
                {
                    if (!string.IsNullOrEmpty(_jsonFilterString))
                    {
                        //serialize the json strig passed by jqGrid
                        var ser = new JavaScriptSerializer();
                        var filter = ser.Deserialize<JqGridFilter>(_jsonFilterString);

                        if (filter != null)
                        {
                            _filter = new PageExtensionHelperFilter
                            {
                                GroupOn = GroupOn(filter.groupOp),
                                Rules = filter.rules.Select(p => new PagingExtensionHelperFilterRule
                                {
                                    FilterField = p.field,
                                    FilterOperator = MapOperator(p.op),
                                    FilterValue = p.data
                                }).ToList()
                            };

                        }
                    }
                }

                return _filter;
            }
        }

        #region Helper Methods

        private static ComparisonOperator MapOperator(string mOperator)
        {
            //['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc'] 
            //['equal','not equal', 'less', 'less or equal','greater','greater or equal', 'begins with','does not begin with','is in','is not in','ends with','does not end with','contains','does not contain'] 
            var returnValue = ComparisonOperator.Equal;

            if (mOperator.Equals("eq", StringComparison.InvariantCultureIgnoreCase))
                returnValue = ComparisonOperator.Equal;
            else if (mOperator.Equals("ne", StringComparison.InvariantCultureIgnoreCase))
                returnValue = ComparisonOperator.NotEqual;
            else if (mOperator.Equals("lt", StringComparison.InvariantCultureIgnoreCase))
                returnValue = ComparisonOperator.Less;
            else if (mOperator.Equals("le", StringComparison.InvariantCultureIgnoreCase))
                returnValue = ComparisonOperator.LessOrEqual;
            else if (mOperator.Equals("gt", StringComparison.InvariantCultureIgnoreCase))
                returnValue = ComparisonOperator.Greater;
            else if (mOperator.Equals("ge", StringComparison.InvariantCultureIgnoreCase))
                returnValue = ComparisonOperator.GreaterOrEqual;
            else if (mOperator.Equals("bw", StringComparison.InvariantCultureIgnoreCase))
                returnValue = ComparisonOperator.StartsWith;
            else if (mOperator.Equals("bn", StringComparison.InvariantCultureIgnoreCase))
                returnValue = ComparisonOperator.DoesNotStartsWith;
            else if (mOperator.Equals("in", StringComparison.InvariantCultureIgnoreCase))
                returnValue = ComparisonOperator.IsIn;
            else if (mOperator.Equals("ni", StringComparison.InvariantCultureIgnoreCase))
                returnValue = ComparisonOperator.IsNotIn;
            else if (mOperator.Equals("ew", StringComparison.InvariantCultureIgnoreCase))
                returnValue = ComparisonOperator.EndsWith;
            else if (mOperator.Equals("en", StringComparison.InvariantCultureIgnoreCase))
                returnValue = ComparisonOperator.DoesNotEndsWith;
            else if (mOperator.Equals("cn", StringComparison.InvariantCultureIgnoreCase))
                returnValue = ComparisonOperator.Contains;
            else if (mOperator.Equals("nc", StringComparison.InvariantCultureIgnoreCase))
                returnValue = ComparisonOperator.DoesNotContains;


            return returnValue;
        }

        private static LogicalOperator GroupOn(string groupOn)
        {
            if (groupOn.Equals("AND", StringComparison.InvariantCultureIgnoreCase))
                return LogicalOperator.And;
            else if (groupOn.Equals("OR", StringComparison.InvariantCultureIgnoreCase))
                return LogicalOperator.Or;
            else
                return LogicalOperator.And;

        }

        #endregion

        #region Filter Helper Class from JqGridFilter
        internal class JqGridFilter
        {
            //TODO: create the enum for group on
            public string groupOp { get; set; }
            public List<JqGridFilterRule> rules { get; set; }
        }

        internal class JqGridFilterRule
        {
            public string field { get; set; }
            public string op { get; set; }
            public string data { get; set; }
        }
        #endregion
    }
}
